/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// @ts-nocheck
import prompt from '@system.prompt';
import router from '@system.router';
import request from '@ohos.request';
import featureAbility from '@ohos.ability.featureAbility';
import mediaLibrary from '@ohos.multimedia.mediaLibrary';

export default{
    data: {
        fileList: [],
        idx: router.getParams()["idx"],
        uid: '',
        //创建一个变量，用来保存当前的索引
        index: 0,
        //显示当前是删除还是撤回
        deleteOrRecall:'删除',
        //创建一个数组来保存撤回、删除
        imgArr: ["撤回", "删除"],

        groupId: '',
        selectedFilePath: [],
        selectedFileName: [],
        selectedFileType: [],
        selectedFileSize: [],
    },
    onInit() {
        console.info('fileSelect=====onInit')
        let context = featureAbility.getContext()
        context.requestPermissionsFromUser(['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA', 'ohos.permission.INTERNET'], 666,(result) => {
            console.info('fileSelect=====requestPermissionsFromUserresult:' + JSON.stringify(result));
        })
    },
    onShow() {
        console.info("fileSelect=====onShow");
        // 获取Documents目录下的文件
        this.listFile();
        this.uid = this.$app.$def.uid;
        this.groupId = this.$app.$def.chatData[this.idx].uid[0];
        console.info("fileSelect=====onshow idx : " + this.idx);
    },
    backToDialogPage(){
        router.back({
            uri: "pages/dialogPage/dialogPage",
        });
    },
    /*
	 * 开启一个定时器，来自动变换文字
	 */
    changeState(){
        //定义一个变量，用来保存定时器的标识
        var timer;
        //在开启定时器之前，需要将当前元素上的其他定时器关闭
        clearTimeout(timer);
        var that = this
        timer = setTimeout(function() {
            //修改img1的src属性
            //使索引自增
            that.changeState();
        }, 120000);
        //判断索引是否超过最大索引
        if(this.index < 2){
            this.$app.$def.deleteOrRecall = this.imgArr[this.index];
            this.index++;
        }
        else{
            clearTimeout(timer);
        }
    },
    sendFile(){
        // 已选择文件的uri
        let FILE_URL = this.selectedFilePath.toString();
        console.info("fileSelect=====File resources selected : " + FILE_URL);
        // 文件消息的消息内容：文件名，文件大小，文件类型
        let messageContent = {
            "fileName": this.selectedFileName.toString(),
            "fileSize": this.selectedFileSize.toString(),
            "fileType": this.selectedFileType.toString(),
        }
        //定时器，撤回转删除
        this.index = 0;
        this.changeState();
        // 发送方将发送的消息放到MsgList
        let timestamp = new Date().getTime().toString() - 28800000;
        this.$app.$def.chatData[this.idx].MsgList.push({isMe: true,
            sendUid:"",
            messageType: 'file',
            content: messageContent,
            profPicUrl:'/common/images/my.jpg',
            createTime:timestamp,});
        let fileType = this.selectedFileType.toString();
        console.info("fileSelect=====fileType : " + fileType);
        let file1 = {filename: this.$app.$def.uid +'-'+ FILE_URL, name: 'file', uri: FILE_URL, type:fileType }
        let fileId = this.guid();
        let data = {};
        // 把文件名放到请求头中，后端需要这个数据
        let header = { "filename": this.selectedFileName.toString()};
        let uploadTask;
        let myUrl = "http://" + this.$app.$def.ip +"/file/fileUpload?fileSignature=" + fileId + "&uid=" +this.$app.$def.uid + "&fileType=" +this.$app.$def.chatData[this.idx].unRead
        console.info("fileSelect=====myUrl : " + myUrl);
        let _this = this;
        request.upload({ url: "http://" + this.$app.$def.ip +"/file/fileUpload?fileSignature=" + fileId + "&uid=" +this.$app.$def.uid + "&fileType=" +this.$app.$def.chatData[this.idx].unRead, header: header, method: "POST", files: [file1], data: [data] }).then((data) => {
            uploadTask = data;
            uploadTask.on('headerReceive', function callback(headers){
                console.info("fileSelect=====upOnHeader headers:" + JSON.stringify(headers));
                // 文件上传成功后，通过TCP发送一条消息
                    _this.socketSendFile(fileId, timestamp);
            });
        }).catch((err) => {
            console.error('fileSelect=====Failed to request the upload. Cause: ' + JSON.stringify(err));
        })
        router.back();
    },
    guid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
    },
    socketSendFile(fileId, timestamp) {
//        let timestamp = new Date().getTime().toString() - 28800000;
        let obj = {}
        let json = {}
        if(this.$app.$def.chatData[this.idx].unRead == 'say'){
            // 单聊的TCP发送
            console.info("fileSelect====>sendFile:type == say " );
            obj = { uid: this.uid, touid: this.$app.$def.chatData[this.idx].uid , role:'ho_user' , type:'say', content:fileId, stype:2,timestamp:timestamp};
            json = JSON.stringify(obj);
            console.info("fileSelect====>sendFile:json == " + json);
        }
        else if(this.$app.$def.chatData[this.idx].unRead == 'group'){
            // 群聊的TCP发送
            console.info("fileSelect====>sendFile:type == group " );
            obj = { uid: this.uid, touid: [this.groupId] , role:'ho_user' , type:'group', content:fileId, stype:2,timestamp:timestamp};
            json = JSON.stringify(obj);
            console.info("fileSelect====>sendFile:json == " + json);
        }
        this.$app.$def.mySocket.send(json)
    },
    chooseFile(obj, e){
        // 文件选择页面，当勾选的时候，拿到对应文件的文件名，路径，类型和大小
        if(e.checked) {
            this.selectedFilePath.push(obj.filePath);
            this.selectedFileName.push(obj.fileName);
            this.selectedFileType.push(obj.fileType);
            this.selectedFileSize.push(obj.fileSize);
        } else {
            prompt.showToast({
                message:'取消勾选 -> checked: ' + e.checked,
                duration: 3000,
            });
        }
    },
    listFile() {
        console.info("fileSelect=====start to search files");
        var context = featureAbility.getContext();
        var media = mediaLibrary.getMediaLibrary(context);
        let fileKeyObj = mediaLibrary.FileKey;
        let fileType = mediaLibrary.MediaType.FILE;
        // filesfetchOp : 文件获取选项，用于检索指定条件下的文件
        let filesfetchOp = {
            selections: fileKeyObj.MEDIA_TYPE + '= ?',
            selectionArgs: [fileType.toString()],
        };
        let _this = this;
        // 获取文件资源，结果放在fileAssetList里面，每一个文件对应一个getAllObjectInfo对象，可通过此对象得到文件名，路径以及文件大小等信息
        media.getFileAssets(filesfetchOp, (error, fetchFileResult) => {
            if (fetchFileResult != undefined) {
                console.info('fileSelect=====mediaLibraryTest : ASSET_CALLBACK fetchFileResult success');
                console.info("fileSelect=====fetch results count : " + fetchFileResult.getCount());
                fetchFileResult.getAllObject((err, fileAssetList) => {
                    if (fileAssetList != undefined) {
                        fileAssetList.forEach(function (getAllObjectInfo) {
                            console.info("fileSelect=====getAllObjectInfo.displayName : " + getAllObjectInfo.displayName);
                            let name = getAllObjectInfo.displayName;
                            let suffix = name.substring(name.lastIndexOf(".") + 1);
                            console.info("fileSelect=====file suffix : " + suffix)
                            console.info("fileSelect=====getAllObjectInfo.uri : " + getAllObjectInfo.uri);
                            console.info("fileSelect=====getAllObjectInfo.size : " + getAllObjectInfo.size);
                            let fileObj = {
                                "fileName": getAllObjectInfo.displayName,
                                "filePath": getAllObjectInfo.uri,
                                "fileSize": getAllObjectInfo.size,
                                "fileType": suffix,
                            };
                            console.info("fileSelect=====fileObj : " + JSON.stringify(fileObj));
                            _this.fileList.push(fileObj);
                        });
                    } else {
                        console.info("fileSelect=====fileAssetList undefined !");
                    }
                });
            } else {
                console.info("fileSelect=====fetchFileResult undefined !");
            }
        });
    },
}